import datetime

from web.utils.bootstrap import BootStrapForm
from django import forms
from web import models
from django.core.validators import ValidationError
from web.myform.widgets import ColorRadioSelect



class ProjectModelForm(BootStrapForm, forms.ModelForm):
    bootstrap_class_exclude = ['color', ]

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']

        widgets = {
            'desc': forms.Textarea,
            # 'color': forms.RadioSelect,
            'color': ColorRadioSelect,
        }

    def __init__(self,request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request


    def clean_name(self):
        name = self.cleaned_data.get('name')
        # 项目名唯一性校验,判断的一个用户不能创建同名的项目
        exists = models.Project.objects.filter(name=name, creator=self.request.tracer_obj.user_obj).exists()

        if exists:
            raise ValidationError('项目名冲突啦！')

        # 获取当前用户已经创建的项目数量
        count = models.Project.objects.filter(creator=self.request.tracer_obj.user_obj).count()

        if count >= self.request.tracer_obj.price_policy.project_num:
            raise ValidationError('项目个数已超量，请花钱，不然创建不了')

        return name



